<template>
    <el-dialog :visible.sync="dialog" :title="isAdd ? '新增用户' : '编辑用户'" append-to-body width="800px">

        <el-form ref="form" :model="form" :rules="rules" size="small" label-width="80px">
            <el-form-item label="账号" prop="userId">
                <el-input v-model="form.userId" style="width: 360px;" placeholder="请输入账号" @change="toUserId()"  clearable/>
            </el-form-item>
            <el-form-item label="密码" prop="password">
                <el-input v-model="form.password" style="width: 360px;" placeholder="请输入密码" maxlength="10" clearable/>
            </el-form-item>

            <el-form-item label="姓名" prop="userName">
                <el-input v-model="form.userName" style="width: 360px;" placeholder="请输入姓名" maxlength="16" minlength="6" clearable/>
            </el-form-item>
     
            <el-form-item label="手机号" prop="mobile">
                <el-input v-model="form.mobile" style="width: 360px;" placeholder="请输入手机号"  clearable/>
            </el-form-item>

            <el-form-item label="身份证号" prop="cardId">
                <el-input v-model="form.cardId" style="width: 360px;" placeholder="请输入身份证号"  clearable/>
            </el-form-item>

            <el-form-item label="用户类型" prop="userType">
                 <el-select v-model="form.userType" clearable placeholder="请选择" style="width: 360px;" @change="toQuery()">
                    <el-option
                      v-for="item in options"
                      :key="item.value"
                      :label="item.label"
                      :value="item.value">
                    </el-option>
                  </el-select>
            </el-form-item>

            <el-form-item label="所属角色" prop="roleIds">
                <el-select v-model="form.roleIds" clearable multiple :multiple-limit="2" filterable placeholder="请选择" style="width: 360px;">
                    <el-option
                        v-for="item in roles"
                        :key="item.id"
                        :label="item.roleName"
                        :value="item.id">
                    </el-option>
                </el-select>
            </el-form-item>

            <el-form-item label="是否启用" prop="status">
                <el-radio v-model="form.status" :label="0">启用</el-radio>
                <el-radio v-model="form.status" :label="1">禁用</el-radio>
            </el-form-item>

            <el-form-item label="用户简介">
                <div style="margin: 20px 0;"></div>
                <el-input v-model="form.remark" style="width: 370px;" rows="5" type="textarea" maxlength="20"  clearable show-word-limit />
            </el-form-item>
        </el-form>

        <div slot="footer" class="dialog-footer">
            <el-button type="text" @click="cancel">取消</el-button>
            <el-button :loading="loading" type="primary" @click="doSubmit" :disabled="this.disabled">确认</el-button>
        </div>
    </el-dialog>
</template>

<script>
import { userSave, getRoles } from '@/api/request'
import { valitoUserId } from '@/api/data'
import { validateUserId,validatPass } from '@/utils/validate'
import { editUser } from '@/api/data'
export default {
    props: {
        isAdd: {
          type: Boolean,
          required: true
        },
    },
    data() {
        const validateuserId = (rule, value, callback) => {
            if (value.trim().length < 1) {
                callback(new Error('用户账号不能为空'))
            } 
            if (!validateUserId(value)) {
                callback(new Error('请输入正确的用户账号'))
            } 
            else {
                callback()
            }
        };
        const validatepassword = (rule, value, callback) => {
            if (value.trim().length < 1) {
                callback(new Error('密码不能为空'))
            } 
            if (!validatPass(value)) {
                callback(new Error('请输入正确的密码'))
            } 
            else {
                callback()
            }
        };
        const validateuserType = (rule, value, callback) => {
            if(value.trim().length < 1){
                callback(new Error('用户类型不能为空'))
            }
            else {
                callback()
            }
        };
        return {
            disabled:true,
            loading: false, dialog: false, permissions: [],
            form: { id:'',userId: '', password: '',userName:'', mobile:'', userType:'',status: 0,cardId:'',roleIds:[],remark:'' },
            rules: {
                userId: [
                    { required: true, trigger: 'blur',validator: validateuserId,},
                    {
                        min: 4,
                        max: 11,
                        message: '账号长度在 4 到 11个字符,字母大小写和数字',
                        trigger: 'blur',
                    }
                ],
                password: [
                    { required: true, trigger: 'blur',validator: validatepassword,},
                    {
                        min: 6,
                        max: 16,
                        message: '密码长度在 6 到 16个字符,数字，字母，大小写，特殊字符至少有两种,',
                        trigger: 'blur',
                    }
                ],
                userName:[
                    { required: true, trigger: 'blur',min: 2,max: 16,
                        message: '用户名长度在 2 到 16个字符'},
                ],
                userType:[
                    { required: true, trigger: 'blur',validator: validateuserType,
                        message: '请选择用户类型,'},
                ],

            },
            options: [
                {
                    value: '0',
                    label: '区域用户'
                },
                {
                    value: '1',
                    label: '老师'
                },
                {
                    value: '2',
                    label: '学生'
                },
            ],
            roles:[]
        }
    },
    mounted:function(){
         // this.ready();
    },
    methods: {
        cancel(){
            this.dialog  = false
        },
        doSubmit(){
            if (this.form.userType == "") {
                this.$message({
                    message: '请选择用户类型',
                    type: 'warning'
                });
                return
            }
            if (this.form.roleIds == "") {
                this.$message({
                    message: '请选择角色',
                    type: 'warning'
                });
                return
            }else{
                this.$refs['form'].validate((valid) => {
                    if (valid){
                        userSave(this.form).then(res => { 
                            this.$notify({
                                title: '保存成功',
                                type: 'success',
                                duration: 2500
                            })
                            this.dialog = false
                            this.$parent.init()
                        })
                    }else {
                        return false
                    }
                    
                })
            }
            
        },
        toUserId(){
            if (this.form.userId) {
                valitoUserId(this.form.userId).then(res => {
                        if (res.data === false) {
                            this.disabled = true
                            this.$message({
                                message: '用户账号已存在',
                                type: 'error'
                            });
                        }else{
                            this.disabled = false
                        }
                })
            }else{
                this.disabled = true
                return
            }
        },
        
        async toQuery(){
            let params = {
                "type": this.form.userType
            }
            try {
                let data = await getRoles(params)
                if (!this.form.userType) {
                    this.roles = []
                    this.form.roleIds = []  //clear  roleIds
                    return
                }else{
                    this.roles = data 
                }
                
            } catch (e) {
                console.log(e)
            }
            
        }
        
        
    }
}
</script>

<style scoped>

</style>
